package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.until.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    // json测试：http://127.0.0.1:8081/register  POST
    // @RequestBody的意思：表示将请求体中的JSON数据映射为User对象
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        // 补充is_active和created_time字段
        user.setIsActive(true); // 设置为激活状态（对应数据库1）
        user.setCreatedTime(new Date()); // 设置当前时间
        int i = userService.addUser(user);
        if (i > 0) {
            return Result.success("注册成功");
        }
        return Result.error("注册失败");
    }

    // 登录接口：POST /login
    @PostMapping("/login")
    public Result login(@RequestParam(required = false) String username, @RequestParam(required = false) String password,
                         @RequestBody(required = false) Map<String, String> credentials) {
        // 从请求参数或请求体中获取用户名和密码
        String reqUsername = username;
        String reqPassword = password;
        
        if (reqUsername == null || reqPassword == null) {
            // 如果查询参数为空，尝试从请求体中获取
            if (credentials != null) {
                reqUsername = credentials.get("username");
                reqPassword = credentials.get("password");
            }
        }
        
        if (reqUsername == null || reqPassword == null) {
            return Result.error("用户名和密码不能为空");
        }
        
        User user = userService.findUser(reqUsername, reqPassword);
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUsername());// 生成Token
            jwtUtil.storeToken(token, user.getUsername());// 存储到Redis
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);// Token存入返回结果
            result.put("users", user);// 用户信息存入返回结果
            return Result.success(result);// 返回成功结果
        } else {
            return Result.error("用户名和密码错误");// 返回错误信息
        }
    }
    
    // 退出登录接口
    @PostMapping("/logout")
    public Result logout(@RequestHeader("token") String token) {
        if (token != null && jwtUtil.validateToken(token)) {
            String username = jwtUtil.getUsernameFromToken(token);
            jwtUtil.removeToken(username); // 从Redis中移除Token
            return Result.success("退出登录成功");
        }
        return Result.error("无效的Token");
    }

    // 添加支持前端登录的接口 - 支持表单数据
    @PostMapping("/findUser")
    public Result findUserByForm(@RequestParam String username, @RequestParam String password) {
        return findUserProcess(username, password);
    }
    
    // 添加支持前端登录的接口 - 支持JSON数据
    @PostMapping(value = "/findUser", consumes = "application/json")
    public Result findUserByJSON(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");
        return findUserProcess(username, password);
    }
    
    // 登录处理的公共方法
    private Result findUserProcess(String username, String password) {
        User user = userService.findUser(username, password);
        if (user != null) {
            // 生成 token
            String token = jwtUtil.generateToken(user.getUsername());// 生成Token
            jwtUtil.storeToken(token, user.getUsername());// 存储到Redis
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);// Token存入返回结果
            result.put("users", user);// 用户信息存入返回结果
            return Result.success(result);
        }
        return Result.error("用户名或密码错误");
    }

    // 添加发送重置密码验证码接口
    @PostMapping("/send-reset-code")
    public Result sendResetCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        if (email != null && userService.findUserByEmail(email) != null) {
            userService.sendToEmail(email);
            return Result.success("验证码已发送至邮箱");
        }
        return Result.error("发送失败，该邮箱不存在");
    }

    // 添加重置密码接口
    @PostMapping("/reset-password")
    public Result resetPassword(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String code = request.get("code");
        String newPassword = request.get("newPassword");

        if (userService.checkCode(email, code)) {
            int result = userService.updatePassword(newPassword, email);
            if (result > 0) {
                return Result.success("密码重置成功");
            }
        }
        return Result.error("密码重置失败");
    }

    // 修改密码：http://127.0.0.1:8081/updatePassword?password=123456&email=123456@qq.com  GET
    @GetMapping("/findUserByEmail")
    public Result findUserByEmail(String email){
        User user =  userService.findUserByEmail( email);
        if ( user!=null){
            return Result.success(user);
        }
        else {
            return Result.error("该QQ邮箱号不存在");
        }

    }

    // 给QQ邮箱发送验证码：http://127.0.0.1:8081/sendEmail?toEmail=123456@qq.com  GET
    @GetMapping("/sendEmail")
    public Result sendEmail(String toEmail){
        if (toEmail!=null&& userService.findUserByEmail(toEmail)!=null){
            userService.sendToEmail(toEmail);
            return  Result.success("发送成功");
        }
        return Result.error("发送失败,该QQ邮箱号不存在");

    }


    // 修改密码：http://127.0.0.1:8081/updatePassword?code=123456&password=123456&email=<EMAIL>
    @PutMapping("/updatePassword")
public Result updatePassword(@RequestParam String code,
                           @RequestParam String password,
                           @RequestParam String email) {
    // 判断验证码是否正确，如果正确，就修改密码
    if (userService.checkCode(email, code)) {
        int i = userService.updatePassword(password, email);
        return Result.success("修改密码成功");
    }
    return Result.error("修改密码失败");
}
    
    // 获取所有用户信息的接口
    @GetMapping("/users")
    public Result getAllUsers() {
        try {
            List<User> users = userService.findAllUsers();
            return Result.success(users);
        } catch (Exception e) {
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
    
    // 根据ID获取单个用户信息
    @GetMapping("/users/{userId}")
    public Result getUserById(@PathVariable Integer userId) {
        try {
            User user = userService.findUserById(userId);
            if (user != null) {
                return Result.success(user);
            }
            return Result.error("用户不存在");
        } catch (Exception e) {
            return Result.error("查询用户信息失败: " + e.getMessage());
        }
    }
    
    // 删除用户接口
    @DeleteMapping("/users/{userId}")
    public Result deleteUser(@PathVariable Integer userId) {
        try {
            int result = userService.deleteUserById(userId);
            if (result > 0) {
                return Result.success("用户删除成功");
            }
            return Result.error("用户不存在或删除失败");
        } catch (Exception e) {
            return Result.error("删除用户失败: " + e.getMessage());
        }
    }
    
    // 通过旧密码修改密码
    @PutMapping("/users/{userId}/password")
    public Result updatePasswordWithOld(@PathVariable Integer userId, @RequestBody Map<String, String> request) {
        try {
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            
            if (oldPassword == null || newPassword == null) {
                return Result.error("旧密码和新密码不能为空");
            }
            
            // 调用服务层方法验证旧密码并更新新密码
            boolean success = userService.updatePasswordWithOld(userId, oldPassword, newPassword);
            
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("旧密码错误，密码修改失败");
            }
        } catch (Exception e) {
            return Result.error("密码修改失败: " + e.getMessage());
        }
    }
}